package com.chebaohui.iqs.service.impl.deal.pingan.login;

import java.util.Date;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;

import com.chebaohui.iqs.service.impl.deal.util.StringUtil;


/**
 * 获取平安登录Cookie
 * 
 * @author xielonghai
 *
 */
public class PACookie {
	private static long beforeTime = getTime();// 上次登录时间
	private static String cookie = "";// 登录cookie值
	private static long max = 10*60 * 1000;// 1 * 60 * 60 * 1000;// cookie缓存时间
	private static long loginTime = 0;
	private final static Log log = LogFactory.getLog(PACookie.class);// logger:日志工具.

	/**
	 * 获取cookie值
	 * 
	 * @param loss
	 *            default false<默认未过期>
	 * @return
	 */
	public static String getCookie() {
		return getCookie(false);
	}

	/**
	 * 获取cookie值
	 * 
	 * @param loss
	 *            是否过期
	 * @return
	 */
	public static String getCookie(boolean loss) {
		synchronized (cookie) {// 锁定cookie，访问时这能单独访问，不能同时来访问获取cookie值
			if (StringUtil.isNulls(cookie)) {// cookie空值，通过登录获取cookie
				cookie = getPAKey();
				beforeTime = getTime();
				return cookie;
			}

			if (loss || (getTime() - beforeTime) > max) {// cookie缓存过期，重新登录获取cookie
				cookie = getPAKey();
				beforeTime = getTime();
				return cookie;
			} else {
				return cookie;
			}
		}
	}

	/**
	 * 获取平安登录cookie
	 * 
	 * @return
	 */
	private static String getPAKey() {
		loginTime++;
		cookie = "c:" + getTime();
		log.info("第" + loginTime + "次获取平安登录cookie：" + cookie);
		return cookie;
	}

	/**
	 * 获取时间
	 * 
	 * @return
	 */
	private static long getTime() {
		return new Date().getTime();
	}
}

